import { ref, unref, watch } from 'vue'
import type { Ref } from 'vue'
import type { IChatMessageItem, IUserData } from '@/common/types'
import bridge from '@/common/bridge'
import { ReceiveMessageType, UserTypeEnum } from '@/common/constants'
import { requestMessageData } from '@/manager/api'

export const useVisitor = () => {
  const visitorData = ref<IUserData>({
    userId: '',
    userName: '',
    userAvatar: ''
  })

  watch(visitorData, () => {
    const { userId } = unref(visitorData)
    bridge.register({
      userId,
      userType: UserTypeEnum.VISITOR,
      merchantCode: '一号商户'
    })
  })

  const setVisitorData = (data: IUserData) => {
    visitorData.value = data
  }

  return { visitorData, setVisitorData }
}

export const useService = () => {
  const serviceData = ref<IUserData>({
    userId: '',
    userName: '',
    userAvatar: ''
  })

  const setServiceData = (data: IUserData) => {
    serviceData.value = data
  }

  return { serviceData, setServiceData }
}

export const useMessage = (visitorData: Ref<IUserData>, serviceData: Ref<IUserData>) => {
  const messageList = ref<IChatMessageItem[]>([])

  const getMessageData = async (pageNum = 1) => {
    const data = await requestMessageData({
      visitorId: visitorData.value.userId,
      serviceId: serviceData.value.userId,
      pageNum
    })
    messageList.value = data.list
  }

  const sendMessage = (content: string) => {
    const { userId: serviceId } = unref(serviceData)
    const { userId: visitorId } = unref(visitorData)

    bridge.sendSingleMessage({
      serviceId: serviceId,
      visitorId: visitorId,
      fromUserId: visitorId,
      toUserId: serviceId,
      content
    })

    messageList.value.push({
      key: Date.now().toString(),
      from: UserTypeEnum.VISITOR,
      id: visitorId,
      name: '',
      avatar: '',
      content: content,
      read: false,
      time: Date.now()
    })
  }

  watch(serviceData, async () => {
    await getMessageData()
  })

  bridge.receiveMessage(ReceiveMessageType.SINGLE_SENDING, (data) => {
    messageList.value.push({
      key: Date.now().toString(),
      from: UserTypeEnum.SERVICE,
      id: data.fromUserId,
      name: '',
      avatar: '',
      content: data.content,
      read: false,
      time: Date.now()
    })
  })

  return { messageList, sendMessage }
}
